package be.djdb.generators;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.TreeSet;
import java.util.jar.JarException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import be.djdb.custom.GZException;
import be.djdb.externstuff.tuned.TarEntry;
import be.djdb.externstuff.tuned.TarInputStream;
import be.djdb.manipulators.streams.StreamManipulators;
import be.djdb.utils.Projectresources;
public class ATemplate {
	  private String tolocation = "WWW";
	  private static final boolean DEBUG = true;
	  public ATemplate(String[] argv){
	    for (int i = 0; i < argv.length; i++) {
		      String packname = argv[i];
		    	try{
					getfromzip(packname);
				}catch(ZipException e){
					try{
						getfromjar(packname);
					}catch(JarException e1){
						throw new RuntimeException("Template was not corectly"+"Can not unpack file? " + packname);
					}
					e.printStackTrace();
				} 	      
		    }
		    if (DEBUG){log(Level.WARNING,"All done!");}
		  }
	  	public ATemplate() {
	  	}
		public void getfromjar(String jarname) throws JarException{
			JARorZIP u = new JARorZIP();
			if(!jarname.endsWith(".jar")){throw new JarException("Not a jar file? " + jarname);}
			u.setlocation(tolocation);
			u.unPack(jarname);
			if (DEBUG){log(Level.WARNING,"All done!");}
		}
		public void getfromzip(String zipname) throws ZipException{
			JARorZIP u =new JARorZIP();
			if (!zipname.endsWith(".zip")){throw new ZipException("Not a zip file?" + zipname );}
			u.setlocation(tolocation);
			u.unPack(zipname);
			if (DEBUG){log(Level.WARNING,"All done!");}
		}
		public void setloc(String to){
			tolocation = to;
		}
		public void getfromGZ(String GZname) throws GZException{
			TARorGZ u = new TARorGZ();
			System.out.println(GZname);
			if (!GZname.endsWith(".gz")){throw new GZException("Not a gz file?" + GZname );}
			u.setlocation(tolocation);
			try {
				u.unPack(GZname);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (DEBUG){log(Level.WARNING,"All done!");}
		}
		public void getfromGZ(InputStream GZname) throws GZException{
			TARorGZ u = new TARorGZ();
			try {
				u.unPack(GZname);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (DEBUG){log(Level.WARNING,"All done!");}
		}
		public static void log(Level level, String msg){
	        String tag ="<>>>>*EclipsePlugin--�L Roegiers 80072631156*<<<<>";
	       //this.msg += tag + msg + "<br />";
	       Logger.getLogger(Projectresources.class.getName()).log(level, tag + msg);
	   }
}
class JARorZIP{
	private ZipFile jarorzip;
	private TreeSet dirs_treeset;
	private String pathprefix = "";
	private static final boolean DEBUG = false;
	private byte[] b;
	File actievedir;
	//private StreamManipulators streamreplacer;
	public JARorZIP() {
		b = new byte[1024];//8092
		dirs_treeset = new TreeSet();
	    actievedir = new File(pathprefix);
	    if (actievedir.exists() && actievedir.isDirectory()){actievedir.mkdirs();}//Bestaat dus
	}
	public void setlocation(String toloc){
		this.pathprefix = toloc+ File.separatorChar;
	}
	public void unPack(String fileName){
	    try {
	    	jarorzip = new ZipFile(fileName);
			Enumeration all = jarorzip.entries();
			while (all.hasMoreElements()) {
				getEntry((ZipEntry) all.nextElement());
			}
	    } catch (IOException err) {
	    	if (DEBUG){log(Level.WARNING,"IO Error: " + err);}
	        return;
	    }
	}
	private boolean createdir_ifnotexist(String Dname){
		    if (dirs_treeset.contains(Dname)){return false; }//IS al eens bekeken
	    	if (DEBUG){log(Level.WARNING,"Creating Directory: " + Dname);}
		    actievedir = new File(pathprefix+Dname);
		    if (actievedir.exists() && actievedir.isDirectory()){return true;}//Bestaat dus
			return actievedir.mkdirs();
	}
	protected void getEntry(ZipEntry  entry) throws IOException { 
		  String ename = entry.getName();
		  int ix = ename.lastIndexOf('/');
		  if (ix > 0){
			  if (entry.isDirectory()){
				  if (DEBUG){log(Level.WARNING,"is A Directory " + ename);}
				  createdir_ifnotexist(ename.substring(0, ix));  
			  }else{
				  if (DEBUG){log(Level.WARNING,"is A File  " + ename);}
				  createfile_ifnotexist(entry);
			  }
		  }
	}
	private void setStreamReplace(){
		//TODO Underconstruct Stub stream vervanger voor collectieve maniplulatie van zip/gz (templates)=>name ...
		log(Level.ALL,"FATAL ERROR : under construction");
	}
	protected void createfile_ifnotexist(ZipEntry  e) throws IOException{
		  String ename = e.getName();
		  if (DEBUG){log(Level.WARNING,"Creating " + ename);}
		  FileOutputStream os = new FileOutputStream(pathprefix+ename);
		  /*if (streamreplacer != null){
			  //TODO Underconstruct Stub stream vervanger voor collectieve maniplulatie van zip/gz (templates)=>name ...
		  }*/
		  InputStream is = jarorzip.getInputStream(e);
		  int n = 0;
		  while ((n = is.read(b)) > 0){
			  os.write(b, 0, n);
		  }
		  is.close();
		  os.close();
	}
	public static void log(Level level, String msg){
        String tag ="<>>>>*EclipsePlugin-JARorGZ-�L Roegiers 80072631156*<<<<>";
       //this.msg += tag + msg + "<br />";
       Logger.getLogger(Projectresources.class.getName()).log(level, tag + msg);
   }
}
class TARorGZ{
	private String pathprefix = "";
	private static final boolean DEBUG = true;
	File actievedir;
	public void setlocation(String toloc){
		this.pathprefix = toloc+"/";
	    actievedir = new File(pathprefix);
	    if (actievedir.exists() && actievedir.isDirectory()){return;}//Bestaat dus
		actievedir.mkdirs();
	}
	private void setStreamReplace(){
		//TODO Underconstruct Stub stream vervanger voor collectieve maniplulatie van zip/gz (templates)=>name ...
		log(Level.ALL,"FATAL ERROR : under construction not working at this moment");
	}
	public void unPack(String fileName) throws IOException{
		try {
			unPack(getInputStream(new File(fileName)));
		} catch (Exception e) {
				e.printStackTrace();
		}
	}
	public void unPack(InputStream istream) throws IOException{
		TarInputStream tin = new TarInputStream(istream);
		TarEntry tarEntry = tin.getNextEntry();
        if(new File(this.pathprefix).exists()){
			      while (tarEntry != null){
			    	  String ename =  tarEntry.getName();
			          File destPath = new File(this.pathprefix + File.separatorChar + ename);
			          System.out.println("Processing " + destPath.getAbsoluteFile());
			          if(tarEntry.isDirectory()){
			        	  if (DEBUG){log(Level.WARNING,"is A Directory " + ename);}
			             destPath.mkdir();
			          }else{
			        	  if (DEBUG){log(Level.WARNING,"is A File  " + ename);}
			              FileOutputStream fout = new FileOutputStream(destPath);
			              tin.copyEntryContents(fout);
			              fout.close();
			          }
			         tarEntry = tin.getNextEntry();
			      }
			      tin.close();
		 }else{
			 if (DEBUG){log(Level.WARNING,"dir doesn't exist! " +pathprefix);}   System.out.println();
         }	
	}
	public InputStream getInputStream(File tarFile) throws Exception{
	      return (tarFile.getName().endsWith(".gz"))? new GZIPInputStream(new FileInputStream(tarFile)): new FileInputStream(tarFile);    
	}
	public static void log(Level level, String msg){
         String tag ="<>>>>*EclipsePlugin-TARorGZ-�L Roegiers 80072631156*<<<<>";
        //this.msg += tag + msg + "<br />";
        Logger.getLogger(Projectresources.class.getName()).log(level, tag + msg);
    }
}
 


